var crypto = require('crypto');
var request = require('request');
var util = require('util');
var dateFormat = require('dateformat');

// set ts=4 sts=4 sw=4

if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}
if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str){
    return this.slice(0, str.length) == str;
  };
}

function getSig(accountSid, accountToken, timestamp) {
    var sig = accountSid + accountToken + timestamp;
    return crypto.createHash('md5').update(sig).digest('hex').toUpperCase();
}

function getAuth(accountSid,timestamp) {
    var src = new Buffer(accountSid + ":" + timestamp);
    return src.toString('base64');
}

var UcpaasRestApi = (function() {
    function RestApi(accountSid, accountToken, appId) {
        this.host = 'https://api.ucpaas.com';
        this.softver = '2014-06-30';
        this.useJson = true;
        this.accountSid = accountSid;
        this.accountToken = accountToken;
        this.appId = appId;
    }

    RestApi.prototype = {
        constructor:RestApi,
        templateSMS: function(toNumbers, templateId, param, callback) {
            var nowTime = new Date();
            var timestamp = dateFormat(nowTime, 'yyyymmddHHMMss');
            var signature = getSig(this.accountSid, this.accountToken, timestamp);
            var url = "/" + this.softver + "/Accounts/" + this.accountSid + "/Messages/templateSMS?sig=" + signature;
            //var body = util.format('{"templateSMS":{ "appId":"%s","to":"%s","templateId":"%s","param":"%s"}}', this.appId, toNumbers, templateId, param);
            var self = this;
            var body = {
                "templateSMS": {
                    "appId": self.appId,
                    "to": toNumbers,
                    "templateId": templateId,
                    "param": param
                }
            };

            var options = {
                uri: self.host + url,
                headers: {
                    'Authorization': getAuth(self.accountSid, timestamp),
                    'Accept': "application/json",
                    'Content-Type': 'application/json;charset=utf-8'
                    //'Content-Length': body.length
                },
                json:body
            }

            request.post(options, callback).json(body);
        }
    };

    return RestApi;
})();

var AccountSid = 'input your account';
var AuthToken = 'input your token';
var AppId = 'input your appid';

function sendSMSTest() {
    var restApi = new UcpaasRestApi(AccountSid, AuthToken, AppId);
    restApi.templateSMS('15888888888', '10885', '5555', function(error, response, data){
        if (!error && response.statusCode == 200) {
            console.log("ok:" + JSON.stringify(data));
        } else {
            console.log("error");
            console.log(response);
        }
    });
}

sendSMSTest();

